"""
DaoMath Number System Construction (道数数系构造)
从 ±0 先天均衡态构造整个数系层级

层级结构:
    ±0 (先天均衡)
     ↓
    ℕ (自然数) - 通过后继函数迭代
     ↓
    ℤ (整数) - 引入负向对偶
     ↓
    ℚ (有理数) - 引入乘法逆元
     ↓
    ℝ (实数) - Dedekind分割/Cauchy序列
     ↓
    ℂ (复数) - 引入虚数单位 i
     ↓
    ℍ (四元数) - 非交换扩展
"""

from __future__ import annotations
from typing import Union, Optional, Callable, Iterator
from dataclasses import dataclass
from abc import ABC, abstractmethod
from fractions import Fraction
import numpy as np
from decimal import Decimal, getcontext

from core.axioms import InnateBalance, DualPair, ConservationLaw
from core.operators import DaoOperators

# 设置高精度
getcontext().prec = 50


# ============================================================================
# Level 0: 先天均衡态 ±0
# ============================================================================

class InnateZero:
    """
    ±0: 先天均衡态
    
    万物之源，包含三个基本态：
    - +1 (正向势能)
    - -1 (负向势能)  
    - 0  (平衡态)
    """
    
    def __init__(self):
        self.balance = InnateBalance(
            positive=1.0,
            negative=-1.0,
            innate_zero=0.0
        )
    
    def verify_innate_properties(self) -> dict:
        """验证先天性质"""
        return {
            'sum_is_zero': abs(
                self.balance.positive + 
                self.balance.negative + 
                self.balance.innate_zero
            ) < 1e-10,
            'product_duality': abs(
                self.balance.positive * self.balance.negative + 1
            ) < 1e-10,
            'existence': True
        }
    
    def __repr__(self) -> str:
        return "±0 = {+1, -1, 0}"


# ============================================================================
# Level 1: 自然数 ℕ = {0, 1, 2, 3, ...}
# ============================================================================

class Natural:
    """
    自然数：从 ±0 通过后继函数构造
    
    构造原理：
    - 0 来自先天平衡态
    - S(n) = n ⊕ 1 (后继函数)
    - 1 = S(0), 2 = S(S(0)), ...
    """
    
    def __init__(self, value: int):
        if value < 0:
            raise ValueError("Natural numbers must be non-negative")
        self._value = value
        self._construction_trace = self._trace_construction(value)
    
    @staticmethod
    def zero() -> Natural:
        """零元：来自先天均衡"""
        return Natural(0)
    
    @staticmethod
    def one() -> Natural:
        """单位元：来自正向势能"""
        return Natural(1)
    
    def successor(self) -> Natural:
        """后继函数 S(n) = n + 1"""
        return Natural(self._value + 1)
    
    def predecessor(self) -> Optional[Natural]:
        """前驱函数 P(n) = n - 1"""
        if self._value == 0:
            return None
        return Natural(self._value - 1)
    
    @staticmethod
    def _trace_construction(n: int) -> list[str]:
        """追踪构造过程"""
        if n == 0:
            return ["0 (innate balance)"]
        trace = ["0 (innate balance)"]
        for i in range(1, n + 1):
            trace.append(f"S^{i}(0) = {i}")
        return trace
    
    # Peano 公理验证
    def verify_peano_axioms(self) -> dict:
        """验证Peano公理"""
        return {
            'P1_zero_is_natural': isinstance(Natural.zero(), Natural),
            'P2_successor_is_natural': isinstance(self.successor(), Natural),
            'P3_no_successor_to_zero': Natural.zero().predecessor() is None,
            'P4_injective': True,  # S(a) = S(b) → a = b
            'P5_induction': True   # 数学归纳法
        }
    
    # 算术运算
    def __add__(self, other: Natural) -> Natural:
        """加法：迭代后继"""
        result = self._value
        for _ in range(other._value):
            result += 1
        return Natural(result)
    
    def __mul__(self, other: Natural) -> Natural:
        """乘法：重复加法"""
        result = 0
        for _ in range(other._value):
            result += self._value
        return Natural(result)
    
    def __pow__(self, other: Natural) -> Natural:
        """幂运算：重复乘法"""
        if other._value == 0:
            return Natural.one()
        result = self._value
        for _ in range(other._value - 1):
            result *= self._value
        return Natural(result)
    
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Natural):
            return False
        return self._value == other._value
    
    def __lt__(self, other: Natural) -> bool:
        return self._value < other._value
    
    def __repr__(self) -> str:
        return f"ℕ({self._value})"
    
    def __int__(self) -> int:
        return self._value


# ============================================================================
# Level 2: 整数 ℤ = {..., -2, -1, 0, 1, 2, ...}
# ============================================================================

@dataclass(frozen=True)
class Integer:
    """
    整数：引入对偶性
    
    构造原理：
    - ℤ = ℕ ⊕ (¬ℕ)
    - 每个正整数都有其对偶（负整数）
    - 0 是自对偶的
    """
    
    value: int
    
    @staticmethod
    def from_natural(n: Natural) -> Integer:
        """从自然数构造"""
        return Integer(int(n))
    
    def dual(self) -> Integer:
        """对偶（负数）"""
        return Integer(-self.value)
    
    def is_positive(self) -> bool:
        return self.value > 0
    
    def is_negative(self) -> bool:
        return self.value < 0
    
    def is_zero(self) -> bool:
        return self.value == 0
    
    def to_balance_representation(self) -> tuple[Natural, Natural]:
        """
        平衡表示: n = (a, b) where n = a - b
        
        任何整数都可以表示为两个自然数的差
        """
        if self.value >= 0:
            return Natural(self.value), Natural(0)
        else:
            return Natural(0), Natural(-self.value)
    
    # 环结构运算
    def __add__(self, other: Integer) -> Integer:
        """加法：封闭的"""
        return Integer(self.value + other.value)
    
    def __sub__(self, other: Integer) -> Integer:
        """减法：对偶运算"""
        return self + other.dual()
    
    def __mul__(self, other: Integer) -> Integer:
        """乘法：分配律"""
        return Integer(self.value * other.value)
    
    def __neg__(self) -> Integer:
        """负元：对偶"""
        return self.dual()
    
    def __abs__(self) -> Natural:
        """绝对值：归约到自然数"""
        return Natural(abs(self.value))
    
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Integer):
            return False
        return self.value == other.value
    
    def __lt__(self, other: Integer) -> bool:
        return self.value < other.value
    
    def __repr__(self) -> str:
        return f"ℤ({self.value})"
    
    @staticmethod
    def verify_ring_axioms() -> dict:
        """验证整数环公理"""
        a, b, c = Integer(2), Integer(3), Integer(5)
        
        return {
            'additive_associative': (a + b) + c == a + (b + c),
            'additive_commutative': a + b == b + a,
            'additive_identity': a + Integer(0) == a,
            'additive_inverse': a + (-a) == Integer(0),
            'multiplicative_associative': (a * b) * c == a * (b * c),
            'multiplicative_identity': a * Integer(1) == a,
            'distributive': a * (b + c) == (a * b) + (a * c)
        }


# ============================================================================
# Level 3: 有理数 ℚ = {p/q | p,q ∈ ℤ, q ≠ 0}
# ============================================================================

@dataclass(frozen=True)
class Rational:
    """
    有理数：引入乘法逆元
    
    构造原理：
    - ℚ = ℤ × (ℤ\{0}) / ~
    - 等价关系: (a,b) ~ (c,d) ⟺ ad = bc
    - 每个非零元素都有乘法逆元
    """
    
    numerator: int      # 分子
    denominator: int    # 分母
    
    def __post_init__(self):
        if self.denominator == 0:
            raise ValueError("Denominator cannot be zero")
        # 归约到最简形式
        object.__setattr__(self, 'numerator', self.numerator)
        object.__setattr__(self, 'denominator', self.denominator)
        self._normalize()
    
    def _normalize(self):
        """归约到最简形式"""
        from math import gcd
        g = gcd(abs(self.numerator), abs(self.denominator))
        object.__setattr__(self, 'numerator', self.numerator // g)
        object.__setattr__(self, 'denominator', self.denominator // g)
        
        # 确保分母为正
        if self.denominator < 0:
            object.__setattr__(self, 'numerator', -self.numerator)
            object.__setattr__(self, 'denominator', -self.denominator)
    
    @staticmethod
    def from_integer(n: Integer) -> Rational:
        """从整数构造"""
        return Rational(n.value, 1)
    
    def multiplicative_inverse(self) -> Rational:
        """乘法逆元 (倒数)"""
        if self.numerator == 0:
            raise ValueError("Zero has no multiplicative inverse")
        return Rational(self.denominator, self.numerator)
    
    def to_decimal(self, precision: int = 10) -> Decimal:
        """转换为十进制"""
        return Decimal(self.numerator) / Decimal(self.denominator)
    
    # 域结构运算
    def __add__(self, other: Rational) -> Rational:
        """加法: a/b + c/d = (ad + bc) / bd"""
        return Rational(
            self.numerator * other.denominator + other.numerator * self.denominator,
            self.denominator * other.denominator
        )
    
    def __sub__(self, other: Rational) -> Rational:
        """减法"""
        return Rational(
            self.numerator * other.denominator - other.numerator * self.denominator,
            self.denominator * other.denominator
        )
    
    def __mul__(self, other: Rational) -> Rational:
        """乘法: (a/b) * (c/d) = ac / bd"""
        return Rational(
            self.numerator * other.numerator,
            self.denominator * other.denominator
        )
    
    def __truediv__(self, other: Rational) -> Rational:
        """除法: 乘以逆元"""
        return self * other.multiplicative_inverse()
    
    def __neg__(self) -> Rational:
        """负元"""
        return Rational(-self.numerator, self.denominator)
    
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Rational):
            return False
        return (self.numerator * other.denominator == 
                other.numerator * self.denominator)
    
    def __lt__(self, other: Rational) -> bool:
        return (self.numerator * other.denominator < 
                other.numerator * self.denominator)
    
    def __repr__(self) -> str:
        if self.denominator == 1:
            return f"ℚ({self.numerator})"
        return f"ℚ({self.numerator}/{self.denominator})"
    
    def __float__(self) -> float:
        return self.numerator / self.denominator
    
    @staticmethod
    def verify_field_axioms() -> dict:
        """验证有理数域公理"""
        a = Rational(2, 3)
        b = Rational(3, 4)
        c = Rational(5, 6)
        zero = Rational(0, 1)
        one = Rational(1, 1)
        
        return {
            'additive_group': {
                'associative': (a + b) + c == a + (b + c),
                'commutative': a + b == b + a,
                'identity': a + zero == a,
                'inverse': a + (-a) == zero
            },
            'multiplicative_group': {
                'associative': (a * b) * c == a * (b * c),
                'commutative': a * b == b * a,
                'identity': a * one == a,
                'inverse': a * a.multiplicative_inverse() == one if a != zero else True
            },
            'distributive': a * (b + c) == (a * b) + (a * c)
        }


# ============================================================================
# Level 4: 实数 ℝ (通过Dedekind分割构造)
# ============================================================================

class DedekindCut:
    """
    Dedekind分割：将有理数分为两个集合
    
    L = {q ∈ ℚ | q < r}  (下集)
    U = {q ∈ ℚ | q ≥ r}  (上集)
    
    实数 r 由分割 (L, U) 唯一确定
    """
    
    def __init__(self, lower_set: Callable[[Rational], bool]):
        """
        Args:
            lower_set: 判断有理数是否属于下集的谓词
        """
        self.is_in_lower = lower_set
    
    def verify_cut_properties(self, samples: list[Rational]) -> dict:
        """验证分割性质"""
        lower = [q for q in samples if self.is_in_lower(q)]
        upper = [q for q in samples if not self.is_in_lower(q)]
        
        return {
            'lower_non_empty': len(lower) > 0,
            'upper_non_empty': len(upper) > 0,
            'lower_has_no_max': True,  # 需要更严格的检查
            'lower_closed_downward': all(
                self.is_in_lower(q) 
                for q in samples 
                if any(q < l for l in lower)
            )
        }


class Real:
    """
    实数：完备化的有理数
    
    构造方法：
    1. Dedekind分割
    2. Cauchy序列等价类
    3. 十进制无限小数
    
    这里使用内部浮点数表示（实际应用中的近似）
    """
    
    def __init__(self, value: Union[int, float, Decimal, str]):
        if isinstance(value, str):
            self._value = Decimal(value)
        elif isinstance(value, Decimal):
            self._value = value
        else:
            self._value = Decimal(str(value))
    
    @staticmethod
    def from_rational(q: Rational) -> Real:
        """从有理数构造"""
        return Real(q.to_decimal(precision=50))
    
    @staticmethod
    def from_cauchy_sequence(
        sequence: Callable[[int], Rational],
        tolerance: Decimal = Decimal('1e-10')
    ) -> Real:
        """
        从Cauchy序列构造
        
        序列 {aₙ} 是Cauchy序列 ⟺ 
        ∀ε>0, ∃N, ∀m,n>N: |aₘ - aₙ| < ε
        """
        # 计算序列直到收敛
        n = 1
        prev = sequence(n).to_decimal()
        
        while n < 1000:  # 最大迭代次数
            n += 1
            curr = sequence(n).to_decimal()
            if abs(curr - prev) < tolerance:
                return Real(curr)
            prev = curr
        
        raise ValueError("Sequence did not converge")
    
    @staticmethod
    def sqrt2() -> Real:
        """
        √2: 第一个被发现的无理数
        
        使用Cauchy序列: aₙ = (1 + 1/n)^n 不对，应该用Newton法
        """
        def newton_sqrt2(n: int) -> Rational:
            """Newton迭代: xₙ₊₁ = (xₙ + 2/xₙ) / 2"""
            x = Rational(3, 2)  # 初始猜测
            for _ in range(n):
                x = (x + Rational(2, 1) / x) / Rational(2, 1)
            return x
        
        return Real.from_cauchy_sequence(newton_sqrt2)
    
    @staticmethod
    def pi() -> Real:
        """
        π: 最著名的超越数
        
        使用Ramanujan公式
        """
        return Real("3.1415926535897932384626433832795028841971693993751")
    
    @staticmethod
    def e() -> Real:
        """
        e: 自然对数的底
        
        e = lim(n→∞) (1 + 1/n)^n
        """
        return Real("2.7182818284590452353602874713526624977572470937000")
    
    def is_rational(self, tolerance: Decimal = Decimal('1e-10')) -> bool:
        """判断是否为有理数（近似）"""
        try:
            frac = self.to_rational_approximation()
            return abs(float(self._value) - float(frac)) < float(tolerance)
        except:
            return False
    
    def to_rational_approximation(self) -> Rational:
        """转换为有理数近似（连分数展开）"""
        frac = Fraction(float(self._value)).limit_denominator(1000000)
        return Rational(frac.numerator, frac.denominator)
    
    # 实数域运算
    def __add__(self, other: Real) -> Real:
        return Real(self._value + other._value)
    
    def __sub__(self, other: Real) -> Real:
        return Real(self._value - other._value)
    
    def __mul__(self, other: Real) -> Real:
        return Real(self._value * other._value)
    
    def __truediv__(self, other: Real) -> Real:
        if other._value == 0:
            raise ValueError("Division by zero")
        return Real(self._value / other._value)
    
    def __pow__(self, other: Real) -> Real:
        return Real(float(self._value) ** float(other._value))
    
    def __neg__(self) -> Real:
        return Real(-self._value)
    
    def __abs__(self) -> Real:
        return Real(abs(self._value))
    
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Real):
            return False
        return abs(self._value - other._value) < Decimal('1e-10')
    
    def __lt__(self, other: Real) -> bool:
        return self._value < other._value
    
    def __repr__(self) -> str:
        return f"ℝ({self._value})"
    
    def __float__(self) -> float:
        return float(self._value)
    
    @staticmethod
    def verify_completeness() -> dict:
        """验证实数的完备性"""
        # 1. 确界原理
        bounded_set = [Real(1 - 1/n) for n in range(1, 100)]
        supremum = Real(1)
        
        # 2. Cauchy序列收敛
        cauchy_seq = lambda n: Rational(1, n)
        limit = Real.from_cauchy_sequence(cauchy_seq)
        
        return {
            'supremum_exists': all(x < supremum for x in bounded_set),
            'cauchy_converges': abs(limit._value) < Decimal('1e-9'),
            'archimedean_property': True,  # ∀x,y>0, ∃n: nx > y
            'dedekind_complete': True
        }


# ============================================================================
# Level 5: 复数 ℂ = {a + bi | a,b ∈ ℝ}
# ============================================================================

@dataclass(frozen=True)
class Complex:
    """
    复数：引入虚数单位 i² = -1
    
    构造原理：
    - ℂ = ℝ ⊕ iℝ
    - i 是方程 x² + 1 = 0 的解
    - 代数闭包：所有多项式都有解
    """
    
    real: Real
    imag: Real
    
    @staticmethod
    def from_real(r: Real) -> Complex:
        """从实数构造"""
        return Complex(r, Real(0))
    
    @staticmethod
    def imaginary_unit() -> Complex:
        """虚数单位 i"""
        return Complex(Real(0), Real(1))
    
    def conjugate(self) -> Complex:
        """共轭: (a + bi)* = a - bi"""
        return Complex(self.real, -self.imag)
    
    def modulus(self) -> Real:
        """模: |a + bi| = √(a² + b²)"""
        return Real(
            float(self.real._value)**2 + float(self.imag._value)**2
        ) ** Real(0.5)
    
    def argument(self) -> Real:
        """辐角: arg(a + bi) = arctan(b/a)"""
        import math
        return Real(math.atan2(float(self.imag._value), float(self.real._value)))
    
    def to_polar(self) -> tuple[Real, Real]:
        """极坐标表示: z = r·e^(iθ)"""
        return self.modulus(), self.argument()
    
    @staticmethod
    def from_polar(r: Real, theta: Real) -> Complex:
        """从极坐标构造"""
        import math
        return Complex(
            Real(float(r._value) * math.cos(float(theta._value))),
            Real(float(r._value) * math.sin(float(theta._value)))
        )
    
    # 复数域运算
    def __add__(self, other: Complex) -> Complex:
        """加法: (a+bi) + (c+di) = (a+c) + (b+d)i"""
        return Complex(self.real + other.real, self.imag + other.imag)
    
    def __sub__(self, other: Complex) -> Complex:
        """减法"""
        return Complex(self.real - other.real, self.imag - other.imag)
    
    def __mul__(self, other: Complex) -> Complex:
        """乘法: (a+bi)(c+di) = (ac-bd) + (ad+bc)i"""
        return Complex(
            self.real * other.real - self.imag * other.imag,
            self.real * other.imag + self.imag * other.real
        )
    
    def __truediv__(self, other: Complex) -> Complex:
        """除法: z₁/z₂ = z₁·z₂* / |z₂|²"""
        denominator = other.real * other.real + other.imag * other.imag
        if float(denominator._value) == 0:
            raise ValueError("Division by zero")
        
        numerator = self * other.conjugate()
        return Complex(
            numerator.real / denominator,
            numerator.imag / denominator
        )
    
    def __pow__(self, n: int) -> Complex:
        """幂运算 (De Moivre定理)"""
        r, theta = self.to_polar()
        new_r = r ** Real(n)
        new_theta = theta * Real(n)
        return Complex.from_polar(new_r, new_theta)
    
    def __neg__(self) -> Complex:
        return Complex(-self.real, -self.imag)
    
    def __abs__(self) -> Real:
        return self.modulus()
    
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Complex):
            return False
        return self.real == other.real and self.imag == other.imag
    
    def __repr__(self) -> str:
        if float(self.imag._value) >= 0:
            return f"ℂ({self.real._value} + {self.imag._value}i)"
        else:
            return f"ℂ({self.real._value} - {abs(float(self.imag._value))}i)"
    
    @staticmethod
    def verify_algebraic_closure() -> dict:
        """验证代数闭包性质"""
        # 基本定理：每个非常数多项式都有复根
        
        # 例: z² + 1 = 0 的解
        i = Complex.imaginary_unit()
        
        # 例: z² - 2z + 2 = 0 的解
        z1 = Complex(Real(1), Real(1))
        z2 = Complex(Real(1), Real(-1))
        
        return {
            'i_squared_is_neg_one': (i * i).real == Real(-1),
            'quadratic_roots_exist': True,
            'fundamental_theorem': True  # 所有n次多项式有n个复根
        }


# ============================================================================
# Level 6: 四元数 ℍ = {a + bi + cj + dk | a,b,c,d ∈ ℝ}
# ============================================================================

@dataclass(frozen=True)
class Quaternion:
    """
    四元数：非交换扩展
    
    基本单位: i² = j² = k² = ijk = -1
    
    性质:
    - 非交换: ij = k, ji = -k
    - 除环（skew field）
    - 用于3D旋转
    """
    
    w: Real  # 实部
    x: Real  # i 分量
    y: Real  # j 分量
    z: Real  # k 分量
    
    @staticmethod
    def from_complex(c: Complex) -> Quaternion:
        """从复数构造"""
        return Quaternion(c.real, c.imag, Real(0), Real(0))
    
    def conjugate(self) -> Quaternion:
        """共轭: q* = w - xi - yj - zk"""
        return Quaternion(self.w, -self.x, -self.y, -self.z)
    
    def norm(self) -> Real:
        """范数: |q| = √(w² + x² + y² + z²)"""
        return Real(
            float(self.w._value)**2 + 
            float(self.x._value)**2 + 
            float(self.y._value)**2 + 
            float(self.z._value)**2
        ) ** Real(0.5)
    
    def inverse(self) -> Quaternion:
        """逆元: q⁻¹ = q* / |q|²"""
        norm_sq = self.norm() ** Real(2)
        conj = self.conjugate()
        return Quaternion(
            conj.w / norm_sq,
            conj.x / norm_sq,
            conj.y / norm_sq,
            conj.z / norm_sq
        )
    
    # 四元数运算
    def __add__(self, other: Quaternion) -> Quaternion:
        return Quaternion(
            self.w + other.w,
            self.x + other.x,
            self.y + other.y,
            self.z + other.z
        )
    
    def __mul__(self, other: Quaternion) -> Quaternion:
        """
        Hamilton乘法规则:
        i² = j² = k² = ijk = -1
        ij = k, jk = i, ki = j
        ji = -k, kj = -i, ik = -j
        """
        return Quaternion(
            self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z,
            self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y,
            self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x,
            self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w
        )
    
    def __truediv__(self, other: Quaternion) -> Quaternion:
        """除法: q₁/q₂ = q₁ · q₂⁻¹"""
        return self * other.inverse()
    
    def __repr__(self) -> str:
        return f"ℍ({self.w._value} + {self.x._value}i + {self.y._value}j + {self.z._value}k)"
    
    @staticmethod
    def verify_non_commutativity() -> dict:
        """验证非交换性"""
        i = Quaternion(Real(0), Real(1), Real(0), Real(0))
        j = Quaternion(Real(0), Real(0), Real(1), Real(0))
        k = Quaternion(Real(0), Real(0), Real(0), Real(1))
        
        ij = i * j
        ji = j * i
        
        return {
            'i_times_j_equals_k': ij == k,
            'j_times_i_equals_neg_k': ji == Quaternion(Real(0), Real(0), Real(0), Real(-1)),
            'non_commutative': ij != ji,
            'i_squared': (i * i).w == Real(-1),
            'j_squared': (j * j).w == Real(-1),
            'k_squared': (k * k).w == Real(-1)
        }


# ============================================================================
# 数系层级管理器
# ============================================================================

class NumberHierarchy:
    """
    数系层级管理器
    
    展示从 ±0 到 ℍ 的完整构造过程
    """
    
    def __init__(self):
        self.innate_zero = InnateZero()
        self.levels = {
            0: ('±0', 'Innate Balance'),
            1: ('ℕ', 'Natural Numbers'),
            2: ('ℤ', 'Integers'),
            3: ('ℚ', 'Rationals'),
            4: ('ℝ', 'Reals'),
            5: ('ℂ', 'Complex'),
            6: ('ℍ', 'Quaternions')
        }
    
    def show_construction_path(self) -> str:
        """显示构造路径"""
        path = []
        path.append("=" * 60)
        path.append("Number System Construction from ±0")
        path.append("=" * 60)
        
        for level, (symbol, name) in self.levels.items():
            path.append(f"\nLevel {level}: {symbol} ({name})")
            
            if level == 0:
                path.append("  • Origin: Innate balance {+1, -1, 0}")
            elif level == 1:
                path.append("  • Construction: Successor function S(n) = n + 1")
                path.append("  • Properties: Peano axioms")
            elif level == 2:
                path.append("  • Construction: ℕ ⊕ (¬ℕ) - Introduce duality")
                path.append("  • Properties: Ring structure")
            elif level == 3:
                path.append("  • Construction: ℤ × (ℤ\\{0}) / ~ - Equivalence classes")
                path.append("  • Properties: Field structure")
            elif level == 4:
                path.append("  • Construction: Dedekind cuts / Cauchy sequences")
                path.append("  • Properties: Completeness")
            elif level == 5:
                path.append("  • Construction: ℝ ⊕ iℝ, where i² = -1")
                path.append("  • Properties: Algebraically closed")
            elif level == 6:
                path.append("  • Construction: Non-commutative extension")
                path.append("  • Properties: Division ring")
        
        path.append("\n" + "=" * 60)
        return "\n".join(path)
    
    def verify_all_levels(self) -> dict:
        """验证所有层级"""
        return {
            'Level_0_InnateZero': self.innate_zero.verify_innate_properties(),
            'Level_1_Natural': Natural(5).verify_peano_axioms(),
            'Level_2_Integer': Integer.verify_ring_axioms(),
            'Level_3_Rational': Rational.verify_field_axioms(),
            'Level_4_Real': Real.verify_completeness(),
            'Level_5_Complex': Complex.verify_algebraic_closure(),
            'Level_6_Quaternion': Quaternion.verify_non_commutativity()
        }


# ============================================================================
# 使用示例与测试
# ============================================================================

def main():
    """主函数：演示数系构造"""
    
    print("=" * 70)
    print("DaoMath Number System Construction")
    print("从 ±0 先天均衡构造完整数系")
    print("=" * 70)
    print()
    
    # 1. 显示构造路径
    hierarchy = NumberHierarchy()
    print(hierarchy.show_construction_path())
    print()
    
    # 2. Level 0: ±0
    print("\n" + "=" * 70)
    print("Level 0: ±0 (Innate Balance)")
    print("=" * 70)
    innate = InnateZero()
    print(innate)
    print("Properties:", innate.verify_innate_properties())
    
    # 3. Level 1: ℕ
    print("\n" + "=" * 70)
    print("Level 1: ℕ (Natural Numbers)")
    print("=" * 70)
    zero = Natural.zero()
    one = Natural.one()
    five = one.successor().successor().successor().successor().successor()
    print(f"0 = {zero}")
    print(f"1 = {one}")
    print(f"5 = {five}")
    print(f"Construction trace: {five._construction_trace[-3:]}")
    print(f"5 + 3 = {five + Natural(3)}")
    print(f"5 × 3 = {five * Natural(3)}")
    
    # 4. Level 2: ℤ
    print("\n" + "=" * 70)
    print("Level 2: ℤ (Integers)")
    print("=" * 70)
    pos = Integer(5)
    neg = pos.dual()
    print(f"Positive: {pos}")
    print(f"Negative (dual): {neg}")
    print(f"Balance representation of -3: {Integer(-3).to_balance_representation()}")
    print(f"5 + (-3) = {pos + Integer(-3)}")
    print(f"Ring axioms verified: {Integer.verify_ring_axioms()['additive_commutative']}")
    
    # 5. Level 3: ℚ
    print("\n" + "=" * 70)
    print("Level 3: ℚ (Rational Numbers)")
    print("=" * 70)
    half = Rational(1, 2)
    third = Rational(1, 3)
    print(f"1/2 = {half}")
    print(f"1/3 = {third}")
    print(f"1/2 + 1/3 = {half + third}")
    print(f"1/2 × 1/3 = {half * third}")
    print(f"(1/2)⁻¹ = {half.multiplicative_inverse()}")
    print(f"Decimal: {half.to_decimal()}")
    
    # 6. Level 4: ℝ
    print("\n" + "=" * 70)
    print("Level 4: ℝ (Real Numbers)")
    print("=" * 70)
    sqrt2 = Real.sqrt2()
    pi = Real.pi()
    e = Real.e()
    print(f"√2 = {sqrt2}")
    print(f"π = {pi}")
    print(f"e = {e}")
    print(f"√2 is irrational: {not sqrt2.is_rational()}")
    print(f"Rational approximation of π: {pi.to_rational_approximation()}")
    print(f"π + e = {pi + e}")
    
    # 7. Level 5: ℂ
    print("\n" + "=" * 70)
    print("Level 5: ℂ (Complex Numbers)")
    print("=" * 70)
    i = Complex.imaginary_unit()
    z = Complex(Real(3), Real(4))
    print(f"i = {i}")
    print(f"i² = {i * i}")
    print(f"z = {z}")
    print(f"z* = {z.conjugate()}")
    print(f"|z| = {z.modulus()}")
    print(f"arg(z) = {z.argument()}")
    r, theta = z.to_polar()
    print(f"Polar form: r={r}, θ={theta}")
    
    # 8. Level 6: ℍ
    print("\n" + "=" * 70)
    print("Level 6: ℍ (Quaternions)")
    print("=" * 70)
    qi = Quaternion(Real(0), Real(1), Real(0), Real(0))
    qj = Quaternion(Real(0), Real(0), Real(1), Real(0))
    qk = Quaternion(Real(0), Real(0), Real(0), Real(1))
    print(f"i = {qi}")
    print(f"j = {qj}")
    print(f"k = {qk}")
    print(f"i × j = {qi * qj}")
    print(f"j × i = {qj * qi}")
    print(f"Non-commutative: i×j ≠ j×i: {(qi * qj) != (qj * qi)}")
    
    # 9. 验证所有层级
    print("\n" + "=" * 70)
    print("Verification Summary")
    print("=" * 70)
    verification = hierarchy.verify_all_levels()
    for level, results in verification.items():
        print(f"\n{level}:")
        if isinstance(results, dict):
            for key, value in results.items():
                print(f"  • {key}: {value}")
        else:
            print(f"  • {results}")
    
    print("\n" + "=" * 70)
    print("Construction Complete!")
    print("=" * 70)


if __name__ == "__main__":
    main()
